/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.util;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Conversion service utility/provider.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-16 18:06
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
abstract public class ConversionUtils {
    @Getter private static final ConversionService conversionService;

    static {
        Set<Object> customizedConverters = new HashSet<>();
        customizedConverters.add(new LongToDate());
        customizedConverters.add(new DateToLong());

        ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
        factory.setConverters(customizedConverters);
        factory.afterPropertiesSet();
        conversionService = factory.getObject();
    }

    public static class LongToDate implements Converter<Long, Date> {
        @Override
        public Date convert(Long source) {
            return source == null ? null : new Date((source));
        }
    }

    public static class DateToLong implements Converter<Date, Long> {
        @Override
        public Long convert(Date source) {
            return source == null ? null : source.getTime();
        }
    }

    public static Integer toInt(Object source) {
        return conversionService.convert(source, Integer.class);
    }

    public static Long toLong(Object source) {
        return conversionService.convert(source, Long.class);
    }

    public static Boolean toBoolean(Object source) {
        return conversionService.convert(source, Boolean.class);
    }

    public static String toString(Object source) {
        return conversionService.convert(source, String.class);
    }
}
